package com.bluefish.bltuan.action.user;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;

import com.bluefish.bltuan.action.OpenAction;
import com.bluefish.bltuan.module.user.User;
import com.bluefish.bltuan.tools.ActionUtil;

@Results({
    @Result(name = "toIndex", type = "redirect", location = "/"),
    @Result(name = "toIndex", type = "redirect", location = "/"),
})
public class LoginAction extends OpenAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8449276921949820369L;

    private static final int LOGIN_SUCCESS = 400;
	
    private int loginMsg;
    
	private String email;

    private String password;
	
	public int getLoginMsg() {
		return loginMsg;
	}

	public void setLoginMsg(int loginMsg) {
		this.loginMsg = loginMsg;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public HttpHeaders create() {
		if(toLogin()){
			return new DefaultHttpHeaders("toIndex").disableCaching();
		}else{
			return new DefaultHttpHeaders(INDEX).disableCaching();
			/*redirect();
			return null;*/
		}
	}

	@Override
	public String destroy() {
		return null;
	}

	@Override
	public String edit() {
		return null;
	}

	@Override
	public HttpHeaders editNew() {
		return null;
	}

	@Override
	public HttpHeaders index() {
		super.index();
		return new DefaultHttpHeaders(INDEX).disableCaching();
	}

	@Override
	public HttpHeaders show() {
		return null;
	}

	@Override
	public String update() {
		return null;
	}
	
	public String login(){
		if(ActionUtil.getCurrentUserId() != null)
			ActionUtil.removeUserId();
		if(ActionUtil.getCurrentUserRight() != null)
			ActionUtil.removeCurrentUserRight();
		return "toIndex";
	}
	
	private boolean toLogin(){
		User user =  this.getUserService().doLogin(this.email, this.password);
		boolean isSuccess = false;
		if(user != null && user.isActivated()){
			ActionUtil.storeCurrentUserID(user.getId());
			ActionUtil.storeCurrentUserRight(user.getUserRight());
			this.loginMsg = LOGIN_SUCCESS;
			isSuccess = true;
		}else {
			this.loginMsg = this.getUserService().validateUser(this.email, this.password);
		}
		return isSuccess;
	}
	
}
